package ctn.web.home.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jmesa.core.filter.DateFilterMatcher;
import org.jmesa.core.filter.MatcherKey;
import org.jmesa.limit.ExportType;
import org.jmesa.limit.Limit;
import org.jmesa.model.PageItems;
import org.jmesa.model.TableModel;
import org.jmesa.model.TableModelUtils;
import org.jmesa.view.component.Table;
import org.jmesa.view.editor.CellEditor;
import org.jmesa.view.editor.DateCellEditor;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlTable;
import org.jmesa.view.html.event.RowEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import ctn.contant.FunContant;
import ctn.contant.PlugContant;
import ctn.service.dto.FunDTO;
import ctn.service.dto.SpecDTO;
import ctn.service.inteface.FunService;
import ctn.util.CTNUserUtil;
import ctn.util.StringUtils;
import ctn.util.jmesa.DateUtils;
import ctn.util.jmesa.PageFilter;
import ctn.util.jmesa.PageSorter;
import ctn.util.jmesa.PaginationCriteria;
import ctn.util.jmesa.TableFacadeUtils;

@Controller
public class FunController {
	@Autowired
	@Qualifier("filePro")
	private Properties filePro;

	@Autowired
	private FunService funServiceImpl;

	@RequestMapping(value = "/main/viewfun")
	public ModelAndView wfunction(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("fun/funShow");
		final Long cpaidParm;
		if(!StringUtils.isEmptyString(request.getParameter("cpaid"))&&!"null".equalsIgnoreCase(request.getParameter("cpaid"))){
			cpaidParm=new Long(request.getParameter("cpaid"));
		}else{
			cpaidParm=null;
		}
		final Long veridParm;
		if(!StringUtils.isEmptyString(request.getParameter("verid"))&&!"null".equalsIgnoreCase(request.getParameter("verid"))){			
			veridParm=new Long(request.getParameter("verid"));
		}else{
			veridParm=null;
		}
		TableModel tableModel = new TableModel("wfun", request, response);
		tableModel.setStateAttr("restore");
		tableModel.setExportTypes(new ExportType[] { ExportType.EXCEL });
		final PaginationCriteria criteria = new PaginationCriteria();
		//criteria.
		//request.getParameter("id");
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "createDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "CompleteDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "startDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "planEndDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.setItems(new PageItems() {
			
			@Override
			public int getTotalRows(Limit limit) {
				PageFilter pageFilter = TableFacadeUtils.getPageFilter(limit,
						FunDTO.class);
				if(null!=cpaidParm){
					pageFilter.addFilter("cpaid", cpaidParm);
					pageFilter.addFilter("verid", veridParm);
				}
				criteria.setPageFilter(pageFilter);

				return funServiceImpl.getWfunListCount(criteria).intValue();
			}

			@Override
			public List<FunDTO> getItems(Limit limit) {
				PageSorter pageSorter = TableFacadeUtils.getPageSorter(limit);
				int rowStart = limit.getRowSelect().getRowStart();
				int rowEnd = limit.getRowSelect().getRowEnd();
				criteria.setPageSorter(pageSorter);
				criteria.setRowStart(rowStart);
				criteria.setRowEnd(rowEnd);
				return   funServiceImpl.getWfunList(criteria);
			}
		});
		 if (tableModel.isExporting()) {
	            tableModel.setTable(getExportTable(cpaidParm));
	        } else {
	            tableModel.setTable(getHtmlTable(cpaidParm));
	        }
		   String view = tableModel.render();
	        if (view == null) {
	            return null; // an export
	        } else {
	            // Setting a parameter to signal that this is an Ajax request.
	            String ajax = request.getParameter("ajax");
	            if (ajax != null && ajax.equals("true")) {
	                byte[] contents = view.getBytes();
	                response.getOutputStream().write(contents);
	                return null;
	            } else { // Not using Ajax if invoke the controller for the first time.
	                mv.addObject("wfunhtml", view); // Set the Html in the request for the JSP.
	                mv.addObject("cpaid",cpaidParm);
	                mv.addObject("verid",cpaidParm);
	            }
	        }
	        int currentUserId=CTNUserUtil.getUser().getId().intValue();
	        if(null!=request.getParameter("userid")){
	        	if((currentUserId==new Long(request.getParameter("userid")).intValue())){    		
		    		request.setAttribute("isCreate", "Y");
		    	}else{
		    		request.setAttribute("isCreate", "N");
		        		
		    	}
	        }
	        
	        return mv;
	}
	
	private Table getExportTable(Long cpaid) {
        Table table = TableModelUtils.createTable("ID","funName","implUserId","completeDate","startDate","planEndDate","createDate","status","level","stage");
        table.setCaption(" 模块管理");
        //模块名称	模块状态	预计人天	创建时间	开发者	开始时间	操作
        table.getRow().getColumn("ID").setTitle("编号");
        table.getRow().getColumn("funName").setTitle("模块名称");
        table.getRow().getColumn("status").setTitle("模块状态"); 
        table.getRow().getColumn("createDate").setTitle("创建日期");
        table.getRow().getColumn("level").setTitle("模块级别"); 
        table.getRow().getColumn("stage").setTitle("预计人工"); 
        table.getRow().getColumn("startDate").setTitle("开发者	开始时间");
        table.getRow().getColumn("planEndDate").setTitle("开发者完成日期");
        return table;
    }

    private Table getHtmlTable(Long cpaid) {
        HtmlTable htmlTable  = TableModelUtils.createHtmlTable("ID","funName","createDate","startDate","status","implUserId","planEndDate","level","stage","action");
        htmlTable.setCaption("模块管理");
        htmlTable.getRow().setOnmouseover(new RowEvent(){

			@Override
			public String execute(Object item, int rowcount) {
				return "showDescInfo("+((FunDTO)item).getID()+")";
			}
        	
        });
        htmlTable.setStyle("width:90%;");
        htmlTable.getRow().getColumn("ID").setTitle("编号");
        htmlTable.getRow().getColumn("ID").setWidth("5%");
        htmlTable.getRow().getColumn("funName").setTitle("模块名称");
        htmlTable.getRow().getColumn("funName").setWidth("15%");
        htmlTable.getRow().getColumn("status").setTitle("状态");
        htmlTable.getRow().getColumn("status").setWidth("5%");
        htmlTable.getRow().getColumn("createDate").setTitle("创建日期");
        htmlTable.getRow().getColumn("createDate").setWidth("10%");
        htmlTable.getRow().getColumn("createDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
        htmlTable.getRow().getColumn("level").setTitle("模块级别");
        htmlTable.getRow().getColumn("level").setWidth("10%");
        htmlTable.getRow().getColumn("stage").setTitle("预计人天");
        htmlTable.getRow().getColumn("stage").setWidth("5%");
        htmlTable.getRow().getColumn("implUserId").setTitle("开发员");
        htmlTable.getRow().getColumn("implUserId").setWidth("10%");
        htmlTable.getRow().getColumn("startDate").setTitle("开发者开始时间");
        htmlTable.getRow().getColumn("startDate").setWidth("10%");
        htmlTable.getRow().getColumn("startDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
        htmlTable.getRow().getColumn("startDate").setSortable(false);
        htmlTable.getRow().getColumn("planEndDate").setTitle("开发者完成日期");
        htmlTable.getRow().getColumn("planEndDate").setWidth("10%");
        htmlTable.getRow().getColumn("planEndDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
        htmlTable.getRow().getColumn("planEndDate").setSortable(false);
        //htmlTable.getRow().getColumn("version").setSortable(false);
        HtmlColumn action=htmlTable.getRow().getColumn("action");
        action.setTitle("操作");
        action.setWidth("15%");
        action.setCellEditor(new CellEditor() {
			
			@Override
			public Object getValue(Object item, String property, int rowcount) {
				FunDTO dto=(FunDTO)item;
				HtmlBuilder html = new HtmlBuilder(); 
				
				
				if(FunContant.STATUS_DEVELOP.equalsIgnoreCase(dto.getStatus())){
					if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateName())){
						html.ahref("./editfun?id="+dto.getID(), "编辑").aEnd();	
						html.nbsp();
					}
					
				}
				if(FunContant.STATUS_WAIT.equalsIgnoreCase(dto.getStatus())){
					//<A HREF="javascript:window.open()">链接</A>
					//html.a().append(" HREF=''").aEnd();
					html.ahref("javascript: toacceptfun("+dto.getID()+")", "接受").aEnd();
					//html.ahref("./toacceptfun?id="+dto.getID(), "接受").aEnd();
					html.nbsp();
					if(CTNUserUtil.getUser().getName().equalsIgnoreCase(dto.getCreateName())){
						html.ahref("./editfun?id="+dto.getID(), "编辑").aEnd();	
						html.nbsp();
					}
			
				}
			
				
				html.ahref("./viewdetail?funid="+dto.getID(), "详细").aEnd();
				html.nbsp();
				html.ahref("./listSpec?verid="+dto.getVerId()+"&funid="+dto.getID(), "下载文档").aEnd();	
				html.nbsp();
				
				return html.toString();
			}
		});
        return htmlTable;
    }
    
    @RequestMapping(value = "/main/viewdetail")
    public  ModelAndView viewdetail(HttpServletRequest request,
  			HttpServletResponse response) throws Exception {
    	ModelAndView mv=new ModelAndView("fun/addfun");
    	//FunDTO dto=new FunDTO();
    
    	String idStr =request.getParameter("funid");
    	FunDTO dto=funServiceImpl.getWfun(new Long(idStr));
    	 
    	request.setAttribute("isEdit", "N");
    	
    	mv.addObject("funDTO", dto);
    	return mv;
    }
    
    @RequestMapping(value = "/main/preaddfun")
    public  ModelAndView preaddfun(HttpServletRequest request,
  			HttpServletResponse response) throws Exception {
    	ModelAndView mv=new ModelAndView("fun/addfun");
    	String parentPath = filePro.getProperty("common.file.spec");
    	FunDTO dto=new FunDTO();
    	Long cpaid=new Long(request.getParameter("cpaid"));
    	Long verid=new Long(request.getParameter("verid"));
    	dto.setCpaID(cpaid);
    	dto.setVerId(verid);
    	dto.setFilePath(parentPath);
//    	dto.setVerId(verid);
    	mv.addObject("funDTO", dto);
    	request.setAttribute("isEdit", "Y");
    	//mv.addObject("verid", verid);
    	//mv.addObject("cpaid", cpaid);
    	return mv;
    }
    @RequestMapping(value = "/main/addfun")
  	public ModelAndView addFun(HttpServletRequest request,
  			HttpServletResponse response,@ModelAttribute("funDTO")FunDTO funDTO, BindingResult errors) throws Exception {
      	ModelAndView mv=new ModelAndView("fun/success");
      	if(StringUtils.isEmptyString(funDTO.getFunName())){
      		errors.rejectValue("funName", null,  "模块名称不能为空。");
      	}
      	if(!StringUtils.isEmptyString(funDTO.getPlanEndDateStr())){
    		Date effDate=DateUtils.parse("yyyy-MM-dd", funDTO.getPlanEndDateStr());
    		if(effDate.before(new Date())){
    			errors.rejectValue("planEndDateStr", null,  "生效日期不能早于今天");
    		}
    	}
      	if(errors.hasErrors()){
      		mv.setViewName("fun/addfun");
      	}else{
      		
      		funDTO.setCreateDate(new Date());
      		funDTO.setStatus(PlugContant.FUN_STATUS_WAIT);
      		funDTO.setCreateName(CTNUserUtil.getUser().getName());
      		funServiceImpl.saveFun(funDTO);
      		
      	}
      	
      	uploadFile(funDTO);
      	request.setAttribute("isEdit", "Y");
      	mv.addObject("capid",funDTO.getCpaID());
      	mv.addObject("verid", funDTO.getVerId());
      	mv.addObject("userid", CTNUserUtil.getUser().getId());
      	return mv;
     }
    
    @RequestMapping(value = "/main/toacceptfun")
    public ModelAndView  toacceptfun(HttpServletRequest request,
  			HttpServletResponse response,@ModelAttribute("funDTO")FunDTO funDTO, BindingResult errors) throws Exception {
    	ModelAndView mv=new ModelAndView("fun/success");
    	String idStr =request.getParameter("funid");
    	if(!StringUtils.isEmptyString(idStr)){
    		funDTO=funServiceImpl.getWfun(new Long(idStr));
    		funDTO.setStatus(PlugContant.FUN_STATUS_DOING);
    		funDTO.setImplUserId(CTNUserUtil.getUser().getId().toString());
    		funServiceImpl.saveFun(funDTO);
    	}
    	
    	
    	return mv;
    }
    @RequestMapping(value = "/main/preeditfun")
    public  ModelAndView preeditfun(HttpServletRequest request,
  			HttpServletResponse response) throws Exception {
    	ModelAndView mv=new ModelAndView("fun/editfun");
    	Long funid=new Long(request.getParameter("id"));
    	FunDTO dto=funServiceImpl.getWfun(funid);
    	mv.addObject("funDTO", dto);
    	return mv;
    }
    @RequestMapping(value = "/main/editfun")
    public  ModelAndView editfun(HttpServletRequest request,
  			HttpServletResponse response,@ModelAttribute("funDTO")FunDTO funDTO, BindingResult errors) throws Exception {
    	ModelAndView mv=new ModelAndView("fun/success");
    	if(!StringUtils.isEmptyString(funDTO.getPlanEndDateStr())){
    		Date effDate=DateUtils.parse("yyyy-MM-dd", funDTO.getPlanEndDateStr());
    		if(effDate.before(new Date())){
    			errors.rejectValue("effDateStr", null,  "生效日期不能早于今天");
    		}
    	}if(errors.hasErrors()){
      		mv.setViewName("fun/editfun");
      	}else{
      		
      	}
    	funServiceImpl.editFun(funDTO);
    	return mv;
    }
    
    private void uploadFile(FunDTO funDTO)throws Exception{
    	if (funDTO.getUpFile() == null) {
			//errors.rejectValue("upFile", null, "文件路径不能为空。");
		} else {
			
			CommonsMultipartFile uf = funDTO.getUpFile();
			String cpaID="";
			if(funDTO.getCpaID()!=null){
				cpaID=funDTO.getCpaID().toString();
			}
			String id="";
			if(funDTO.getID()!=null){
			 id=funDTO.getID().toString();
				
			}
			String verid="";
			if(funDTO.getVerId()!=null){
				verid=funDTO.getVerId().toString();
				
			}
			File fileDir = new File(funDTO.getFilePath()+"/"+cpaID+"/"+verid +"/"+id+"/"+DateUtils.formatDateTime("yyyyMMdd", new Date()) );
			if(!fileDir.exists()){
				fileDir.mkdirs();
			}
			File file = new File(fileDir, uf.getOriginalFilename());
			//plugDTO.getID();
			//plugDTO.getVerID();
			SpecDTO specDTO=new SpecDTO();
			specDTO.setCreateDate(new Date());
			specDTO.setCreateUserName(CTNUserUtil.getUser().getName());
			specDTO.setSpecTyp("fun");
			//specServiceImpl.saveSpec(specDTO);
			BufferedOutputStream os = null;
			BufferedInputStream is = null;
			try {
				os = new BufferedOutputStream(new FileOutputStream(file));
				is = new BufferedInputStream(uf.getInputStream());

				byte[] byteA;
				int read = 0;
				while (read != -1) {
					byteA = new byte[1024];
					read = is.read(byteA);
					if (read != -1) {
						os.write(byteA, 0, read);
					}
				}
				os.flush();
			} finally {
				if (is != null) {
					is.close();
				}
				if (os != null) {
					try {
						os.close();
					} catch (Exception ex) {
					}
				}
			}
		}
    	
    }
}
